//
//  TimeUtil.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2022/10/25.
//  Copyright © 2022 zwb. All rights reserved.
//

import UIKit

final class TimeCalibrateUtil:NSObject {
    
    private override init() {}
    static let shared = TimeCalibrateUtil()
    
    var timer :Timer?
    
    func startTimer() {
        if self.timer.isNone {
            self.timer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(self.tickDown), userInfo:nil, repeats:true)
        }
    }
    
   private func closeTimer() {
        if timer.isSome {
            timer!.invalidate()
            timer = nil
        }
    }
    // 时间修正，如果服务器时间和本地时间差距多于30秒，那么每次对比时间都用这个修正
    var nowTimeFix:Int = 0
    
    
    @objc func tickDown(){
        
 
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        var now = Date()
//                KSLog("local:\(now)")

        let serverNow = now.addingTimeInterval(TimeInterval(self.nowTimeFix))
        
        let userInfo = ["servertime_data": serverNow]
//        KSLog("server:\(serverNow)")
        let notification = Notification(name: Notification.Name(rawValue: "servertime_notification"), object: nil, userInfo: userInfo)
        NotificationCenter.default.post(notification)
        
         
        
    }
    
    // 校验服务器时间
    func getServerTime() {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        KSNetwork.shared.doRequest(API.getServerTime,showHud: false) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                if let infoStr = data.infoStr {
                    
                    var serverDDD = Date()
                    if let endD = dateFormatter.date(from: infoStr) {
                        serverDDD = endD
                    }
                    
                    let timeNumber = Int(serverDDD.timeIntervalSince1970-dateFormatter.date(from: Date.nowTimeToSecond)!.timeIntervalSince1970)
                    if timeNumber > 30 || timeNumber < -30 {
                        // 服务器时间和本地时间差距超过30秒
                        self.nowTimeFix = timeNumber
                    } else {
                        self.nowTimeFix = 0
                    }
                }
            }
        }
    }
    
    
}
